from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.utils import timezone

from common.views import AuthTemplateView, AuthMobileTemplateView
from groupshopping.models import GroupShopping
from product.models import Product
from shop.models import ShopInfo
from shop.serializers import ShopInfoSerializer


class ShopDataView(AuthTemplateView):
    """店铺首页数据"""
    template_name = 'shop/shop_data.html'

    def get_context_data(self, **kwargs):
        kwargs['secure'] = self.request.is_secure()
        return super(ShopDataView, self).get_context_data(**kwargs)


class ShopAddView(AuthTemplateView):
    template_name = 'shop/shop_add.html'

    def get_context_data(self, **kwargs):
        kwargs['admin'] = self.request.user
        kwargs['shop'] = kwargs['admin'].get_shop()
        kwargs['secure'] = self.request.is_secure()
        return super(ShopAddView, self).get_context_data(**kwargs)

    def post(self, request, *args, **kwargs):
        serializer = ShopInfoSerializer(data=request.POST)
        if serializer.is_valid():
            serializer.save(user=request.user, status=ShopInfo.STATUS_VALID)
            return JsonResponse({'status': 0, 'detail': 'success'})
        else:
            return JsonResponse({'status': 1, 'detail': serializer.errors})


class MobileShopHomeView(AuthMobileTemplateView):
    template_name = 'mobile/home.html'

    def get_context_data(self, **kwargs):
        kwargs['product_list'] = Product.objects.filter(shelve=True, status=Product.STATUS_VALID)[:9]
        kwargs['groupshopping_recommends'] = GroupShopping.objects.filter(shelve=True, status=Product.STATUS_VALID)[:2]
        return super(MobileShopHomeView, self).get_context_data(**kwargs)

    def get(self, request, *args, **kwargs):
        return super(MobileShopHomeView, self).get(self, request, *args, **kwargs)
